<template>
  <div class="login-container">
    <el-row class="" justify="center">
      <el-col :span="14">
        <div class="login-head">
          <div class="container">
            <img
              v-if="env.VITE_RELEASE_NAME === 'fendi'"
              class="login-left-img"
              src="@/assets/images/logo-black-fendi.png"
              alt="login"
            />
            <img
              v-if="env.VITE_RELEASE_NAME === 'shangtuo'"
              class="login-left-img"
              src="@/assets/images/logo-black-shangtuo.png"
              alt="login"
            />
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row class="login-main" justify="center" align="middle">
      <el-col :span="14">
        <el-row :gutter="80">
          <el-col :span="12">
            <div class="img-bx">
              <img
                v-if="env.VITE_RELEASE_NAME === 'fendi'"
                class="introduce-image"
                src="@/assets/images/login-bg-fendi.png"
                alt="login-bg"
              />
              <img
                v-if="env.VITE_RELEASE_NAME === 'shangtuo'"
                class="introduce-image"
                src="@/assets/images/login-bg-shangtuo.png"
                alt="login-bg"
              />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="login-box">
              <el-text class="fsize20">注册</el-text>
              <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="env.VITE_RELEASE_NAME === 'fendi' ? rules1 : rules2"
                class="mt20"
                status-icon
              >
                <el-form-item label="" prop="mobile">
                  <el-input v-model="ruleForm.mobile" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="" prop="passWord">
                  <el-input type="password" v-model="ruleForm.passWord" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="" prop="storeName">
                  <el-input v-model="ruleForm.storeName" placeholder="请输入门店名称" />
                </el-form-item>
                <el-form-item label="" prop="industryId">
                  <el-select class="w100" v-model="ruleForm.industryId" placeholder="请选择行业">
                    <el-option v-for="item in industryList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="" prop="areaObject">
                  <el-cascader
                    class="w100"
                    v-model="ruleForm.areaObject"
                    :options="pcaCode"
                    :props="{ value: 'code', label: 'name' }"
                    placeholder="请选择所属区域"
                  />
                </el-form-item>
                <el-form-item label="" prop="activationCode">
                  <el-input-number
                    class="w100"
                    v-model="ruleForm.activationCode"
                    :controls="false"
                    placeholder="请输入邀请码,没有可不填"
                  />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input v-model="ruleForm.code" placeholder="请输入验证码">
                    <template #prefix>
                      <span class="input-prefix-text">验证码</span>
                    </template>
                    <template #suffix>
                      <div @click.stop>
                        <el-button
                          @click="getCaptcha"
                          :disabled="codeText === '获取验证码' ? false : true"
                          text
                          class="input-suffix-text"
                        >
                          {{ codeText }}
                        </el-button>
                      </div>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button class="w100 height48" type="primary" @click="submitForm(ruleFormRef)">注册</el-button>
                </el-form-item>
              </el-form>
              <div class="mt20 flx-row-reverse">
                <el-text class="pointer fsize14" size="large" @click="goLogin">已有账号? 立即登录</el-text>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="register">
import { reactive, ref, onMounted, unref } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { LOGIN_URL } from "@/config";
import { getIndustryList, registerStore, sendVeriCode } from "@/api/modules/login";
import pcaCode from "@/assets/json/pcaCode";
import md5 from "js-md5";

const router = useRouter();
const codeText = ref("获取验证码");
const env = ref(import.meta.env);

interface RuleForm {
  mobile: string;
  passWord: string;
  storeName: string;
  industryId: number;
  areaObject: string[];
  code: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  mobile: "",
  passWord: "",
  storeName: "",
  industryId: "",
  areaObject: [],
  code: ""
});
// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else if (ruleForm.mobile === "") {
    // 解释一下为什么要判断用户名不能为空
    // 因为我们的密码校验其中有一项是要校验是否包含用户名，如果用户名不输入，怎么校验？？？

    callback(new Error("请先输入手机号"));
  } else {
    const finalCheckPwd =
      /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;

    // 校验密码
    const checkPwd: boolean = finalCheckPwd.test(ruleForm.passWord);

    if (!checkPwd) {
      callback(new Error("密码必须不少于8位, 包含大小写、字母、字符至少三种"));
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};

// 手机号码自定义验证规则
const telValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入手机号"));
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
const rules1 = reactive<FormRules<RuleForm>>({
  mobile: [{ required: true, validator: telValidator, trigger: "blur" }],
  passWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: validatePass }
  ],
  storeName: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
  industryId: [{ required: true, message: "请选择所属行业", trigger: "blur" }],
  areaObject: [{ required: true, message: "请选择所属区域", trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
});

const rules2 = reactive<FormRules<RuleForm>>({
  mobile: [{ required: true, validator: telValidator, trigger: "blur" }],
  passWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: validatePass }
  ],
  storeName: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
  industryId: [{ required: true, message: "请选择所属行业", trigger: "blur" }],
  areaObject: [{ required: true, message: "请选择所属区域", trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
});
const goLogin = () => {
  router.replace(LOGIN_URL);
};

const getCaptcha = () => {
  const formRef: any = unref(ruleFormRef);
  formRef.validateField("mobile", (valid: boolean) => {
    if (valid) {
      let n = 60;
      sendVeriCode({ mobile: ruleForm.mobile }).then(() => {
        codeText.value = n + "秒钟重新获取";
        const timer = setInterval(() => {
          if (n === 0) {
            clearInterval(timer);
            codeText.value = "获取验证码";
          } else {
            n--;
            codeText.value = n + "秒钟重新获取";
          }
        }, 1000);
      });
    }
  });
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      registerStore({ ...ruleForm, passWord: md5(ruleForm.passWord) }).then(res => {
        ElMessage.success({ message: res.msg });
        router.push(LOGIN_URL);
      });
    }
  });
};
const industryList = ref([]);
onMounted(async () => {
  const [industry] = await Promise.all([getIndustryList({ pageNum: 1, pageSize: 9999 })]);
  industryList.value = industry.data;
});
</script>

<style scoped lang="scss">
@import "./login.scss";
</style>
